package com.mega.ebcs.anttask;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import au.com.bytecode.opencsv.CSVReader;

public class DMLConverterTask extends Task {
	
	Log logger = LogFactory.getLog(DMLConverterTask.class);
	
	private String fromFile;
	private String toFile;
	
	public String getFromFile() {
		return fromFile;
	}
	public void setFromFile(String fromFile) {
		this.fromFile = fromFile;
	}

	public String getToFile() {
		return toFile;
	}
	public void setToFile(String toFile) {
		this.toFile = toFile;
	}
	
	@SuppressWarnings("rawtypes")
	public void execute() throws BuildException {
		List<String> listOfFile = new ArrayList<String>();
		
		try {
			File mergeAll = new File(fromFile);
			
			String folderPath = new File(mergeAll.getParent()).getCanonicalPath();
			
			if (mergeAll.isFile()) {
				BufferedReader inputStream = new BufferedReader(new FileReader(mergeAll));
				
				String line;
				while ((line = inputStream.readLine()) != null) {
					listOfFile.add(folderPath+"/"+line.trim());
				}
				
				inputStream.close();
				
				if(new File(getToFile()).exists()) {
					new File(getToFile()).delete();
				}
				
				FileWriter fileWriter = new FileWriter(getToFile());
				
				for(Iterator<String> iterator=listOfFile.iterator(); iterator.hasNext();) {
					
					String fileName = iterator.next();
					String fileNameWithoutPath = new File(fileName).getName();
					
					if(! new File(fileName).isFile()) {
						logger.error("Cannot read "+fileName+ " for conversion to SQL");
						continue;
					}
					
					String tableName = fileNameWithoutPath.substring(0, fileNameWithoutPath.indexOf("."));
					
					fileWriter.append("-- BEGIN TABLE "+tableName.toUpperCase()+"\r\n");
					
					CSVReader csvReader = new CSVReader(new FileReader(fileName),'\t');
					
					List entries = csvReader.readAll();
					
					if(entries.size() > 0) {
						String[] columnName = (String[]) entries.get(0);
						
						for(int i=1; i<entries.size(); i++) {
							String[] columnValue = (String[]) entries.get(i);
							
							if(columnName.length != columnValue.length) {
								logger.error("column name length != column value length on table: " + tableName);
							}
							
							DMLConverter dml = new DMLConverter(tableName, columnName, columnValue);
							
							fileWriter.append(dml.toString());
						}
					}
					
					fileWriter.append("-- END TABLE "+tableName.toUpperCase()+"\r\n");
					
					csvReader.close();
				}
				
				fileWriter.close();
			} else {
				logger.error("Fail to read " + mergeAll.getCanonicalPath() );
			}
		} catch (Exception e) {
			logger.error("Exception during DML convertion " + e.getMessage(), e );
		}
	}
}
